﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace Devonline.AspNetCore;

/// <summary>
/// 基于 DataService 的数据增删改查的基础控制器
/// </summary>
/// <typeparam name="TDbContext">数据库上下文</typeparam>
/// <typeparam name="TEntitySet">业务数据类型</typeparam>
/// <typeparam name="TKey">主键类型</typeparam>
[Authorize]
[ApiController]
public abstract class DataServiceController<TDbContext, TEntitySet, TKey> :
    ControllerBase
    where TDbContext : DbContext
    where TEntitySet : class, IEntitySet<TKey>
    where TKey : IConvertible
{
    protected readonly ILogger<DataServiceController<TDbContext, TEntitySet, TKey>> _logger;
    protected readonly IDataService<TDbContext, TEntitySet, TKey> _dataService;
    public DataServiceController(
        ILogger<DataServiceController<TDbContext, TEntitySet, TKey>> logger,
        IDataService<TDbContext, TEntitySet, TKey> dataService
        )
    {
        _logger = logger;
        _dataService = dataService;
    }

    #region 因为 Get 方法的路由和 odata get 方法冲突, 因此暂不提供 get/byId 的方法
    ///// <summary>
    ///// 使用 id 查询单个数据对象的 get 请求
    ///// </summary>
    ///// <param name="id"></param>
    ///// <returns></returns>
    //[HttpGet("{id}")]
    //public virtual async Task<IActionResult> GetAsync(TKey id) => Ok(await _dataService.GetAsync<TEntitySet>(id));
    #endregion

    /// <summary>
    /// 新增单个数据对象的 post 请求
    /// </summary>
    /// <param name="entitySet"></param>
    /// <returns></returns>
    [HttpPost]
    public virtual async Task<IActionResult> CreateAsync(TEntitySet entitySet) => Ok(await _dataService.AddAsync(entitySet));

    /// <summary>
    /// 修改单个数据对象的 put 请求
    /// </summary>
    /// <param name="entitySet"></param>
    /// <returns></returns>
    [HttpPut]
    public virtual async Task<IActionResult> UpdateAsync(TEntitySet entitySet) => Ok(await _dataService.UpdateAsync(entitySet));

    /// <summary>
    /// 使用 id 删除单个数据对象的 delete 请求
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public virtual async Task<IActionResult> DeleteAsync(TKey id)
    {
        await _dataService.DeleteAsync(id);
        return Ok();
    }
}

/// <summary>
/// 基于字符串作为主键的 DataService 的数据增删改查的基础控制器
/// </summary>
/// <typeparam name="TDbContext">数据库上下文</typeparam>
/// <typeparam name="TEntitySet">业务数据类型</typeparam>
[Authorize]
[ApiController]
public abstract class DataServiceController<TDbContext, TEntitySet> :
    DataServiceController<TDbContext, TEntitySet, string>
    where TDbContext : DbContext
    where TEntitySet : class, IEntitySet
{
    public DataServiceController(
        ILogger<DataServiceController<TDbContext, TEntitySet>> logger,
        IDataService<TDbContext, TEntitySet> dataService
        ) : base(logger, dataService) { }
}